﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineEducation.Data;
using OnlineEducation.Models.JQueryTable;
using OnlineEducation.Helpers.JQueryTable;
using OnlineEducation.Helpers;
using OnlineEducation.Controllers;

namespace OnlineEducation.Areas.Controllers
{
    [Area("Subject")]
    [Route("[controller]/[action]")]
    [Authorize(Roles = "SuperAdmin,Teacher")]
    public class SubjectController : BaseController
    {

        private readonly ApplicationDbContext _context;
        private readonly ILogger _logger;
        public SubjectController(ApplicationDbContext context, ILogger<SubjectController> logger)
        {
            _context = context;
            _logger = logger;
        }


        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult GetAll(DTParameters param)
        {
            var query = _context.Codes.Where(n => n.Category == Constants.Code.Subject);

            var newQuery = new SortHelper<OnlineEducation.Data.Entities.Code>().Apply(query, param);

            var items = newQuery.Skip(param.Start).Take(param.Length).ToArray();

            var count = newQuery.Count();

            return Json(new DTResult<OnlineEducation.Data.Entities.Code>
            {
                draw = param.Draw,
                data = items,
                recordsFiltered = count,
                recordsTotal = count
            });
        }

        [HttpGet("{id?}")]
        public async Task<IActionResult> AddEdit(int? id)
        {
            if (id.HasValue)
            {
                return View(await _context.Codes.FindAsync(id));
            }
            else
            {
                var template = new OnlineEducation.Data.Entities.Code();

                var count = _context.Codes.Where(n => n.Category == OnlineEducation.Constants.Code.Subject).Count() + 1;

                template.Name = count.ToString().PadRight(4, '0');

                return View(template);

            }
        }

        [HttpPost]
        public async Task<IActionResult> Save([FromBody]OnlineEducation.Data.Entities.Code data)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorMessages());
            }
            try
            {
                if (data.ID <= 0)
                {

                    bool isExistSameName = _context.Codes.Any(n => n.Name == data.Name && n.Category == "Subject");

                    if (isExistSameName) return BadRequest("科目号已存在");

                    bool isExistSameValue = _context.Codes.Any(n => n.Value == data.Value && n.Category == "Subject");

                    if (isExistSameValue) return BadRequest("科目名称已存在");

                    _context.Add(data);

                    await _context.SaveChangesAsync();

                    return Json(new { success = true, message = "新增科目成功." });

                }
                else
                {
                    bool isExistSameValue = _context.Codes.Any(n => n.Value == data.Value && n.Category == "Subject" && n.ID != data.ID);

                    if (isExistSameValue) return BadRequest("科目名称已存在");

                    var subject = await _context.Codes.FindAsync(data.ID);

                    if (subject == null)
                    {
                        return NotFound("科目不存在");
                    }

                    subject.Value = data.Value;

                    _context.Update(subject);

                    await _context.SaveChangesAsync();

                    return Json(new { success = true, message = "更新科目成功." });

                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return Json(new { success = false, message = ex.Message });
            }
        }

        [HttpPost("{id}")]
        public async Task<IActionResult> ChangeStatus(int? id)
        {
            if (!id.HasValue)
            {
                return BadRequest("id为空");
            }

            try
            {
                var code = await _context.Codes.FindAsync(id.Value);

                if (code == null)
                {
                    return NotFound("未找到科目");
                }
                if (code.Status == 1)
                {
                    code.Status = 0;
                }
                else
                {
                    code.Status = 1;
                }

                _context.Update(code);

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "状态变更成功." });
            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message });
            }


        }
        [HttpPost("{id}")]
        public async Task<IActionResult> Delete(int? id)
        {
            if (!id.HasValue)
            {
                return BadRequest("id为空");
            }

            try
            {
                var code = await _context.Codes.FindAsync(id.Value);

                if (code == null)
                {
                    return NotFound();
                }

                _context.Codes.Remove(code);

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "删除科目成功." });
            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message });
            }


        }
    }
}